package com.base.monitor.module.biz.component;

import com.base.monitor.module.biz.mq.MonitorQueueProducer;
import com.base.monitor.module.biz.properties.NetworkProperties;
import com.base.monitor.module.biz.properties.ParamProperties;
import com.base.monitor.module.biz.server.TcpServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.stereotype.Component;

@Component
@EnableConfigurationProperties({NetworkProperties.class, ParamProperties.class})
public class RefreshComponent {
    @Autowired
    private NetworkProperties networkProperties;

    @Autowired
    private TcpServer tcpServer;

    @Value("${receive.queue.name}")
    private String queueName;

    @Autowired
    private ParamProperties paramProperties;

    @Autowired
    private MonitorQueueProducer monitorQueueProducer;

    @Autowired
    private ContextRefresher contextRefresher;

    public void start() {
        // 1.启动服务器
        startTcpServer();
        // 2.启动mq
        startMq();
    }

    /**
     * 启动mq
     */
    private void startMq() {
        new Thread(() -> monitorQueueProducer
                .doInit(paramProperties.getUploadCollectDataUrl(), queueName)).start();
    }

    /**
     * 启动服务器
     */
    private void startTcpServer() {
        new Thread(() -> tcpServer.startServer(networkProperties.getPort())).start();
    }

    public void stop() {
        // 1.停止服务器
        tcpServer.closeServer();
        // 2.停止mq
        monitorQueueProducer.closeProducer();
    }

    public void restart() {
        stop();

        contextRefresher.refresh();

        start();
    }
}
